//
//  RwdOAuthController.swift
//  Weibo_rwd
//
//  Created by 任文迪 on 16/7/10.
//  Copyright © 2016年 spaceX. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

//  微博appKey
let WeiboAppKey = "3587944955"
//  微博appsecret
let WeiboAppSecret = "07474a29da9e1523ae0f4e0152224a94"
//  微博授权回调页
let WeiboRedirect_Uri = "http://www.sina.com"



class RwdOAuthController: UIViewController {
    
    //懒加载一个webview
    lazy var MyWebView: UIWebView = UIWebView()
    
    override func loadView() {
        
        view = MyWebView
        
        MyWebView.delegate = self
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置navigationController的UI
        setupNavUI()
        
        self.view.backgroundColor = UIColor.whiteColor()
        
        requestForOAuthLogin()
        // Do any additional setup after loading the view.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //请求数据
    func requestForOAuthLogin() {
        //设置url
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        //设置request
        let request = NSURLRequest(URL: NSURL(string: url)!)
        //加载请求
        MyWebView.loadRequest(request)
        
        
    }
    
    
    //设置navigationcontroller
    private func setupNavUI() {
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
        
    }
    //左侧返回
    func cancelAction() {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充
    func autoFillAction() {
        
        print("点击了自动填充")
        //swift调JavaScript的方法 自动根据textfield 填充
        MyWebView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '635759583@qq.com'; document.getElementById('passwd').value = 'rwd19910619'")
    }
    
    

    
}


    
extension RwdOAuthController: UIWebViewDelegate {
        
        //通过extention来增加方法
        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
            //如果没有值就返回
            guard let url = request.URL else {
                
                return false
                
            }
            //筛选出需要的那个url
            if !url.absoluteString.hasPrefix(WeiboRedirect_Uri){
                
                return true
                
            }
            
            //截取code
            if let query = url.query where query.hasPrefix("code=") {
                //  截取code
                let code = query.substringFromIndex("code=".endIndex)
                
                print(code)
                //将获取的code调用给accesstoken方法 来获取其他内容
                RwduserAccountViewModel.shareUserAccount.getAccessToken(code, callBack: { (isSuccess) -> () in
                    if isSuccess {
                        
                        print("登陆成功")
                        
                        let rwdhome = RwdCommonController()
                        
                        rwdhome.isLogin = true
                        
                        self.dismissViewControllerAnimated(false, completion: { () -> Void in
                            //发送通知,切换欢迎页控制器
                            NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                            
                        })
                        
                    }else {
                        
                        print("登录失败")
                    }
                    
                    
                })
            } else {
                
                
                dismissViewControllerAnimated(false, completion: nil)
            }
            
            return false
            
            
            
            
            
        }
        
        
        //  开始加载
        
        
        func webViewDidStartLoad(webView: UIWebView) {
            SVProgressHUD.show()
        }
        //  加载完成
        func webViewDidFinishLoad(webView: UIWebView) {
            SVProgressHUD.dismiss()
        }
        //  加载失败
        func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
            SVProgressHUD.dismiss()
        }
        
        
        
        
}


func test() {
    //通过授权码获得code
    //    {
    //    "access_token": "ACCESS_TOKEN",
    //    "expires_in": 1234,
    //    "remind_in":"798114",
    //    "uid":"12341234"
    //    }
    //    //请求方式为post请求
    func getAccessToken(code: String) {
        
        RwdNetworkTools.sharedTools.requestAccesstoken(code) { (response, error) -> () in
            //如果有错误信息返回 那么久打印出来
            if error != nil {
                
                print(error)
                return
            }
            
            guard let dict = response as? [String:AnyObject] else {
                print("格式错误")
                return
            }
            //如果走到这里说明 dict一定存在且有值
            let userAcount = RwdUserAcount(dict: dict)
            
            print(userAcount)
            
            getuserInfos(userAcount)
            
        }
        
    }
    
    
    
    func getuserInfos(userAcount:RwdUserAcount) {
        //通过网络工具类请求数据
        RwdNetworkTools.sharedTools.getuserInfos(userAcount) { (response, error) -> () in
            
            if error != nil {
                
                print(error)
                return
                
            }
            //判断
            guard let dict = response as? [String:AnyObject] else {
                print("格式错误")
                return
            }
            let name = dict["name"]
            let avatar_large = dict["avatar_large"]
            //设置用户名和头像
            userAcount.name = name as?String
            userAcount.avatar_large = avatar_large as?String
            
            //保存
            userAcount.saveToUserData()
            print(userAcount)
        }
        
        
        
        
        
    }
}


